package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private IFollowService followService;
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
           this.queryBlogUser(blog);
           this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    //根据博客id查询博客信息
    @Override
    public Result queryBlogById(Long id) {
        //查询博客
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("笔记不存在");
        }
        //查询博客有关用户
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result updateLikeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id;
        //查询该博客该用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //未点赞，点赞数加一，存入Redis
        if (score == null){
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess){
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            //已经点赞,点赞数减一，移除Redis
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryLikedSorted(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //获取当前博客点赞前top5
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //按ids的顺序查询用户信息
        List<User> users =  blogMapper.selectIds(ids);
        List<UserDTO> userList = users.stream().map(user -> BeanUtil.toBean(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        //查询粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //得到粉丝id
        follows.forEach(follow -> {
            Long userId = follow.getUserId();
            String key = "feed:" + userId;
            //添加到收件箱
            stringRedisTemplate.opsForZSet().add(key ,blog.getId().toString(),System.currentTimeMillis());
        });
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询用户关注博客
     * @param max 最大时间戳
     * @param offset 偏移量
     * @return 滚动列表
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户的ID
        Long userId = UserHolder.getUser().getId();
        //构建Redis中存储关注博客的关键字
        String key = "feed:" + userId;
        //查询当前用户关注的博客收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //如果查询结果为空，则直接返回成功响应
        if (typedTuples == null||typedTuples.isEmpty()){
            return Result.ok();
        }
        //获取博客id,最小时间戳,下次偏移量offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        //初始最小时间戳
        long minTime = 0;
        //初始偏移量
        int os = 1;
        //遍历查询结果，获取博客ID、最小时间戳和下次偏移量
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            //根据时间戳更新最小时间戳和偏移量
            if (time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        //根据id获取博客信息
        List<Blog> blogs = blogMapper.selectByBlogIds(ids);
        //为每个博客查询相关用户和点赞状态
        blogs.forEach(blog -> {
            queryBlogUser(blog);
            isBlogLiked(blog);
        });
        //构建滚动查询结果对象
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setMinTime(minTime);
        result.setOffset(os);
        //返回滚动查询结果
        return Result.ok(result);
    }


    private void isBlogLiked(Blog blog){
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return;
        }
        Long userId = user.getId();
        String key = BLOG_LIKED_KEY + blog.getId();
        //查询该博客该用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);

    }

    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
